<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title">商品分类列表</view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入分类名称搜索" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button v-if="hasPermission('CREATE_PRODUCT_CATEGORY')" class="uni-button" type="primary" size="mini"
					@click="showAddForm">新增</button>
				<button v-if="hasPermission('DELETE_PRODUCT_CATEGORY')" class="uni-button" type="warn" size="mini"
					:disabled="!selectedIndexs.length" @click="delTable">
					批量删除
				</button>
			</view>
		</view>
		<view class="uni-container">
			<!-- 显示列表 -->
			<template v-if="!isAddFormVisible &&!isEditFormVisible">
				<!-- 添加 update_date 字段到 field 属性 -->
				<unicloud-db ref="udb" :collection="collectionList" field="data_id, name, type, sort, update_date" :where="where" page-data="replace"
					:orderby="orderby" :getcount="true" :page-size="options.pageSize"
					:page-current="options.pageCurrent" v-slot:default="{ pagination, loading, error, options }"
					:options="options" loadtime="manual" @load="onqueryload">
					<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
						type="selection" @selection-change="selectionChange">
						<uni-tr>
							<uni-th align="center">分类 ID</uni-th>
							<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'name')"
								sortable @sort-change="sortChange($event, 'name')">分类名称
							</uni-th>
							<uni-th align="center" filter-type="select" :filter-data="options.filterData.categoryTypes"
								@filter-change="filterChange($event, 'type')">分类类型
							</uni-th>
							<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'sort')"
								sortable @sort-change="sortChange($event, 'sort')">排序
							</uni-th>
							<uni-th align="center">操作</uni-th>
						</uni-tr>
						<uni-tr v-for="(item, index) in tableList" :key="index">
							<uni-td align="center">{{ item.data_id }}</uni-td>
							<uni-td align="center">{{ item.name }}</uni-td>
							<uni-td align="center">{{ item.type }}</uni-td>
							<uni-td align="center">{{ item.sort }}</uni-td>
							<uni-td align="center">
								<view class="uni-group">
									<button v-if="hasPermission('UPDATE_PRODUCT_CATEGORY')" @click="showEditForm(item)"
										class="uni-button" size="mini" type="primary">修改
									</button>
									<button v-if="hasPermission('DELETE_PRODUCT_CATEGORY')"
										@click="confirmDelete(item._id)" class="uni-button" size="mini"
										type="warn">删除</button>
								</view>
							</uni-td>
						</uni-tr>
					</uni-table>
					<view class="uni-pagination-box">
						<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
							:total="pagination.count" @change="onPageChanged" />
					</view>
				</unicloud-db>
			</template>
			<!-- 显示新增表单 -->
			<template v-else-if="isAddFormVisible">
				<add-form @cancel="hideAddForm" @submit="hideAddForm"></add-form>
			</template>
			<!-- 显示修改表单 -->
			<template v-else>
				<edit-form :item="editItemData" @cancel="hideEditForm" @submit="hideEditForm"></edit-form>
			</template>
		</view>
	</view>
</template>

<script>
	import authMixin from "@/uni_modules/uni-cms/common/auth-mixin";
	import AddForm from './add.vue';
	import EditForm from './edit.vue'; // 引入修改表单组件

	const db = uniCloud.database()
	const categoryDBName = 'jl_product_categories'

	// 修改排序规则
	const dbOrderBy = 'sort asc, update_date asc'
	const dbSearchFields = ['name']
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		mixins: [authMixin],
		components: {
			AddForm,
			EditForm // 注册修改表单组件
		},
		data() {
			return {
				collectionList: categoryDBName,
				query: '',
				where: undefined,
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"categoryTypes": [
							{
								"value": "基础分类",
								"text": "基础分类"
							},
							{
								"value": "特殊分类",
								"text": "特殊分类"
							}
						]
					}
				},
				tableList: [],
				isAddFormVisible: false,
				isEditFormVisible: false, // 控制修改表单显示的变量
				editItemData: {} // 存储要修改的数据
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {
			showAddForm() {
				this.isAddFormVisible = true
			},
			hideAddForm() {
				this.isAddFormVisible = false
			},
			showEditForm(item) {
				this.editItemData = item
				this.isEditFormVisible = true
			},
			hideEditForm() {
				this.isEditFormVisible = false
			},

			async delTable() {
				const idsToDelete = this.selectedIndexs.map(index => this.tableList[index]._id);
				try {
					await this.$refs.udb.remove(idsToDelete);
					// uni.showToast({ title: '删除成功', icon: 'none' });
					this.selectedIndexs = [];
					this.$refs.table.clearSelection();
					this.$refs.udb.loadData();  // 取消注释这行
				} catch (err) {
					console.error('批量删除失败:', err);
					uni.showToast({ title: '删除失败', icon: 'none' });
				}
			},
			// 搜索方法
			search() {
				const query = this.query.trim();
				if (query) {
					const command = uniCloud.database().command;
					const searchRegex = command.regex({
						regexp: query,
						options: 'i'
					});
					this.where = command.or([
						{ name: searchRegex },
						{ data_id: searchRegex }
					]);
				} else {
					this.where = undefined;
				}
				console.log('search where:', this.where);
				this.$refs.udb.loadData();
			},
			// 筛选条件改变时的处理方法
			filterChange(event, field) {
				this._filter[field] = event;
				this.where = this.filterToWhere();
				console.log('filterChange where:', this.where);
				this.$refs.udb.loadData();
			},
			// 构建筛选查询条件的方法
			filterToWhere() {
				const command = uniCloud.database().command;
				const whereConditions = [];
				for (let key in this._filter) {
					let value = this._filter[key];
					if (value) {
						if (typeof value === 'string') {
							whereConditions.push({ [key]: value });
						} else if (Array.isArray(value)) {
							whereConditions.push({ [key]: command.in(value) });
						} else if (value.filterType === 'search') {
							const searchRegex = command.regex({
								regexp: value.filter,
								options: 'i'
							});
							whereConditions.push({ [key === 'name' ? 'name' : key]: searchRegex });
						} else if (value.filterType === 'range') {
							const min = Number(value[0]);
							const max = Number(value[1]);
							if (!isNaN(min) && !isNaN(max)) {
								whereConditions.push({ [key]: command.gte(min).lte(max) });
							} else if (!isNaN(min)) {
								whereConditions.push({ [key]: command.gte(min) });
							} else if (!isNaN(max)) {
								whereConditions.push({ [key]: command.lte(max) });
							}
						} else if (value !== null && value !== undefined) {
							whereConditions.push({ [key]: value });
						}
					}
				}
				if (whereConditions.length === 0) {
					return undefined;
				}
				if (whereConditions.length === 1) {
					return whereConditions[0];
				}
				return command.and(whereConditions);
			},
			sortChange(event, field) {
				this.orderby = `${field} ${orderByMapping[event]}`
				this.$refs.udb.loadData()
			},
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			onPageChanged(currentPage) {
				this.selectedIndexs.length = 0
				this.options.pageCurrent = currentPage
				this.$refs.udb.loadData()
			},

			onqueryload(data) {
				this.selectedIndexs.length = 0
				this.tableList = data;
				console.log('onqueryload data:', data); // 添加日志输出，检查 data 是否正确
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection();
						// 添加以下两行代码刷新数据
						uni.showToast({ title: '删除成功', icon: 'none' });
						this.$refs.udb.loadData();
					},
					fail: (err) => {
						uni.showToast({ title: '删除失败', icon: 'none' });
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.uni-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
	}

	.uni-group {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.uni-search {
		padding: 10rpx;
		border: 1px solid #eee;
		border-radius: 5rpx;
	}

	.uni-button {
		padding: 10rpx 20rpx;
		border: none;
		border-radius: 5rpx;
		cursor: pointer;
	}

	.uni-container {
		padding: 20rpx;
	}

	.uni-pagination-box {
		margin-top: 20rpx;
		display: flex;
		justify-content: center;
	}
</style>

// 在_execLoadData的catch块中添加错误日志
.catch((err) => {
  console.error('数据库请求失败:', err);
  this.loading = false;
  this._execLoadDataFail(err, callback);
})